package com.kolaxy.chat;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class ChatClient {

    private final String HOST = "127.0.0.1";
    private int PORT = 9999;
    private SocketChannel socketChannel;
    private Selector selector;

    public ChatClient() throws Exception {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        if (!socketChannel.connect(new InetSocketAddress(HOST, PORT))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("还么连上，先干其他事情");
            }
        }

        String userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("-------------Client(" + userName + ") is ready -------------");
    }


    public void sendMsg(String msg) throws Exception {

        if (msg.equals("BYE")) {
            socketChannel.close();
            return;
        }
        ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());

        socketChannel.write(byteBuffer);
    }

    public void read() throws Exception {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int size = socketChannel.read(byteBuffer);

        if (size > 0) {
            System.out.println(new String(byteBuffer.array()).trim());
        }
    }
}
